// databasemanager.cpp
#include "databasemanager.h"

DatabaseManager& DatabaseManager::instance()
{
    static DatabaseManager instance;
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
    return instance;
}

DatabaseManager::DatabaseManager(QObject* parent) : QObject(parent) {
    // QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
}

DatabaseManager::~DatabaseManager()
{
    close();
}

bool DatabaseManager::init(const QString& dbPath)
{
    if (m_db.isOpen()) {
        qWarning() << "Database already initialized!";
        return true;
    }

    // 创建数据库连接（使用唯一名称）
    m_connectionName = "sqlite_connection_" + QString::number(quintptr(this));
    m_db = QSqlDatabase::addDatabase("QSQLITE", m_connectionName);
    m_db.setDatabaseName(dbPath);

    if (!m_db.open()) {
        m_lastError = m_db.lastError().text();
        qCritical() << "Failed to open database:" << m_lastError;
        return false;
    }

    qDebug() << "Database opened successfully.";
    return true;
}

void DatabaseManager::close()
{
    if (m_db.isOpen()) {
        m_db.close();
        QSqlDatabase::removeDatabase(m_connectionName);
        qDebug() << "Database closed.";
    }
}
//using QVariantMap = QMap<QString, QVariant>;
QSqlQuery *DatabaseManager::executeQuery(const QString& query, const QVariantMap& params)
{
    // qDebug()<<"执行语句:"<<query;
    if (!m_db.isOpen()) {
        m_lastError = "Database not initialized!";
        init();//尝试连接数据库
        if(!m_db.isOpen())//仍不能连接上数据库
        {
            qDebug()<<m_lastError;
            return nullptr;
        }
    }
    // qDebug()<<"Database_debug2";
    QSqlQuery *sqlQuery=new QSqlQuery(m_db);
    sqlQuery->prepare(query);
    // qDebug()<<"Database_debug3";
    // 绑定参数
    for (auto it = params.constBegin(); it != params.constEnd(); ++it) {
        sqlQuery->bindValue(":" + it.key(), it.value());
    }
    // qDebug() << "Final SQL:" << sqlQuery->executedQuery();
    // qDebug()<<sqlQuery->lastQuery();
    if (!sqlQuery->exec()) {
        m_lastError = sqlQuery->lastError().text();
        qWarning() << "Query failed:" << m_lastError;
        return nullptr;
    }

    return sqlQuery;
}

QSqlDatabase DatabaseManager::get_db()
{
    init();
    return m_db;
}
//
bool DatabaseManager::tableExists(const QString& tableName)
{
    if (!m_db.isOpen()) {
        m_lastError = "Database not initialized!";
        return false;
    }
    //sqlite_mater保存各表的信息
    QSqlQuery query(m_db);
    query.prepare("SELECT name FROM sqlite_master "
                  "WHERE type='table' AND name=:name");
    query.bindValue(":name", tableName);

    if (!query.exec()) {
        qCritical() << "Table check error:" << query.lastError().text();
        return false;
    }
    return query.next();

}

QString DatabaseManager::lastError() const
{
    return m_lastError;
}
